/*
 * Sphere.cpp
 *
 *  Created on: 19/05/2010
 *      Author: Nadav
 */

#include "Sphere.h"

Sphere::Sphere(Vec3f center, float radius, Vec3f color) {
	this->center = center;
	this->radius = radius;
	this->color = color;
}

Sphere::~Sphere() {

}

bool Sphere::intersect(const Ray &r, Hit &h, float tmin) {
	float a=1;
	Ray transformedRay(r.getDirection(), r.getOrigin()-center);
	float b=2*transformedRay.getDirection().Dot3(transformedRay.getOrigin());
	float c=transformedRay.getOrigin().Dot3(transformedRay.getOrigin()) - radius*radius;
	float discriminant = b*b - 4*a*c;
	if (0>discriminant) return false;
	float t1 = (-b+sqrt(discriminant))/(2*a);
	float t2 = (-b-sqrt(discriminant))/(2*a);
	int legalValuesCount = 0;
	float legals[2];
	if (t1>0 && t1>tmin && t1<h.getT()) legals[legalValuesCount++] = t1;
	if (t2>0 && t2>tmin && t2<h.getT()) legals[legalValuesCount++] = t2;
	if (legalValuesCount == 0) return false;
	float minimalT = legals[0];
	if (legalValuesCount == 2) {
		if (legals[1]<legals[0]) minimalT = legals[1];
	}
	Vec3f normal = getNormal(transformedRay, minimalT);
	h.set(minimalT, color, normal);
	return true;
}

Vec3f Sphere::getNormal(const Ray& r, const float hitPoint) {
//	Vec3f* normal = new Vec3f();
	Vec3f hitPointVec = r.pointAtParameter(hitPoint);
	return hitPointVec - center;
//	*normal = hitPoint - center;
//	return *normal;
}
